package com.easy.order.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easy.common.bean.Order;
import com.easy.common.bean.User;
import com.easy.common.service.IOrderService;
import com.easy.common.service.IUserService;
import com.easy.common.util.Result;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/order")
public class OrderController {
    @DubboReference
    IUserService userService;
    @Autowired
    IOrderService orderService;

    @GetMapping("/{id}")
    public Result getOrderById(@PathVariable Integer id) {
        return Result.success(orderService.getOrderById(id));
    }

    @PostMapping
    public Result addOrder(@RequestBody Order order) {
        int result = orderService.addOrder(order);
        return result > 0 ? Result.success("添加成功", null) : Result.fail(500, "添加失败");
    }

    @PutMapping
    public Result updateOrder(@RequestBody Order order) {
        int result = orderService.updateOrder(order);
        return result > 0 ? Result.success("更新成功", null) : Result.fail(500, "更新失败");
    }

    @DeleteMapping("/{id}")
    public Result deleteOrder(@PathVariable Integer id) {
        int result = orderService.deleteOrder(id);
        return result > 0 ? Result.success("删除成功", null) : Result.fail(500, "删除失败");
    }

    @PostMapping("/list")
    public Result getAll(@RequestBody Order order) {
        return Result.success(orderService.getAll(order));
    }
    
    @PostMapping("/page")
    public Result getPage(@RequestParam(defaultValue = "1") Integer pageNum, 
                                @RequestParam(defaultValue = "10") Integer pageSize, 
                                @RequestBody(required = false) Order order) {
        IPage<Order> page = new Page<>(pageNum, pageSize);
        if (order == null) {
            order = new Order();
        }
        return Result.success(orderService.getPage(order, page));
    }
    
    @RequestMapping("/getOrder")
    public Result getOrder() {
        User user=userService.getUserById(1);
        System.out.println(user);
        return Result.success("getOrder", "getOrder");
    }
    @GlobalTransactional
    @RequestMapping("/addOrder")
    public Result addOrder() {
        User user=userService.getUserById(1);
        user.setId(null);
        userService.addUser(user);
        int a=12/0;
        return Result.success("addOrder", "addOrder");
    }

}
